#!/usr/bin/python
# encoding:utf8

import os
import sys
import json
import hashlib
import binascii

XXTEA_SIGN = "mXjv7U5dUl1aMTVV_xianlai"
XXTEA_KEY = "SQLLiteData"
PACKINFO_FILE_ASSETLIST = "reslist.json"  # assetlist文件列表


def get_xl_file_md5(filename):
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()  # create a md5 object
    f = open(filename, 'rb')
    a = b''
    while True:
        b = f.read(1048576)  # get file content.
        if not b:
            break
        a = a + b
    c = binascii.b2a_hex(a)
    myhash.update(c.upper())
    myhash.update("3c6e0b8a9c15224a8228b9a98ca1531d".encode("utf-8"))
    f.close()
    return myhash.hexdigest()


def crt_assetlist(spath):
    asset_list = dict()
    for root, dirs, files in os.walk(spath):
        for _f in files:
            tf = os.path.join(root, _f)
            asset_list[os.path.relpath(tf, spath)] = dict(
                md5=get_xl_file_md5(tf)
            )
    return asset_list


def filter_f(filename, stype):
    if filename.endswith(".%s" % stype)\
            or filename.startswith("."):
        return True


def cocos_compile(ppath, xxteasign, xxteakey):
    cmd_cocos = "cocos luacompile -s {frompath} -d {topath} -e -k {sign} -b {key} --disable-compile".format(
                frompath=ppath,
                topath=ppath,
                sign=XXTEA_SIGN,
                key=XXTEA_KEY
    )
    os.system(cmd_cocos)
    fileobj = None
    for root, dirs, files in os.walk(ppath):
        for filename in files:
            fileobj = os.path.join(root, filename)
            if filter_f(filename, "lua") and os.path.isfile(fileobj):
                os.remove(fileobj)


def run():
    tmppath = sys.argv[1]
    print(tmppath, "-->>>hook execute tmppath")
    cocos_compile(tmppath, XXTEA_SIGN, XXTEA_KEY)
    fpack = os.path.join(tmppath, PACKINFO_FILE_ASSETLIST)
    with open(fpack, "w") as fp:
        asset_list = crt_assetlist(tmppath)
        fp.write(json.dumps(asset_list, indent=4, sort_keys=True))


if __name__ == "__main__":
    run()
